<template>
  <div>
    <Tabs v-model="showTabPanel" type="card">
      <TabPane name="aTab" label="设备信息" class="padding5">
        <Row :gutter="10">
          <Col span="12">
            <Form ref="formValidate" :model="virtualObj" :rules="ruleValidate" :label-width="80" class="daaa">
              <FormItem label="设备类型" prop="model">
                <Input v-model="virtualObj.model" disabled="disabled" />
              </FormItem>
              <FormItem label="设备名称" prop="name">
                <Input v-model="virtualObj.name" placeholder="设备名称" />
              </FormItem>
              <FormItem label="设备编号" prop="sn">
                <Input v-model="virtualObj.sn" placeholder="设备编号" />
              </FormItem>
              <FormItem label="所属空间" prop="deviceSpaceText">
                <Cascader change-on-select :render-format="cascaderFormat" trigger="click" :data="deviceSpaceData"
                          v-model="virtualObj.deviceSpace">
                  <Input v-model="virtualObj.deviceSpaceText" readonly placeholder="请选择设备空间"></Input>
                </Cascader>
              </FormItem>
              <FormItem label="排序值" prop="sort">
                <Input v-model="virtualObj.sort" placeholder="排序值" />
              </FormItem>
            </Form>
            <Row class="ddxx">
              属性数据
            </Row>
            <div>
              <table class="tableOne">
                <tr>
                  <th style="width: 170px;">名称</th>
                  <th style="width: 170px;">单位</th>
                  <th style="width: 160px;">上限</th>
                  <th style="width: 160px;">下限</th>
                  <th style="width: auto;">操作</th>
                </tr>
              </table>
              <div class="bppp">
                <table class="tableOne">
                  <tr v-for="(item,index) in virtualObj.virtualItems" :key="index"
                      style="cursor: pointer;">
                    <td style="width: 170px;text-align: center">
                      {{item.name}}
                    </td>
                    <td style="width: 170px;text-align: center">
                      {{item.unit}}
                    </td>
                    <td style="width: 160px;text-align: center">
                      {{item.lowLimit}}
                    </td>
                    <td style="width: 160px;text-align: center">
                      {{item.upperLimit}}
                    </td>
                    <!-- <td style="width: 130px;text-align: center">
                      <Input v-model="item.formula" placeholder="计算公式" style="width: 100%" readonly/>
                    </td> -->
                    <td style="width: auto;text-align: center">
                      <Button type="default" size="small" @click="previewItem(item)" icon="ios-search">查看</Button>
                      <Button type="default" size="small" @click="delItem(index)" icon="ios-trash-outline">删除</Button>
                    </td>
                  </tr>
                </table>
              </div>
            </div>
           <!-- <div class="ddqq">
              <Button type="primary" long @click="doSave" :loading="saveingLoading">保存设备</Button>
            </div>-->
          </Col>
          <Col span="12">
            <div class="dxx">
              <Row :gutter="20">
                <Col span="12">
                  <Input v-model="pageable.param" prefix="ios-search-outline" placeholder="搜索内容" @on-enter="doQuery"/>
                </Col>
                <Col span="12" style="text-align: right">
                  <RadioGroup v-model="devType" type="button" @on-change="radioChange">
                    <Radio label="真实设备"></Radio>
                    <Radio label="虚拟设备"></Radio>
                  </RadioGroup>
                </Col>
              </Row>
              <div class="ooa">
                <Table stripe :columns="columns1" :data="data1" size="small" :loading="tableLoading"
                       height="300"></Table>
                <div class="pagg">
                  <Page :current="pageable.page" :page-size="pageable.size" :total="total" simple
                        @on-change="pageChange"/>
                </div>
              </div>
              <div class="ooaa">
                <Row :gutter="5">
                  <Col span="5" push style="margin-right:5px">
                    属性名称<Input v-model="virtualItem.name" placeholder="属性名称"/>
                  </Col>
                  <Col span="4" push style="margin-right: 5px">单位
                    <Select v-model="virtualItem.unit" :transfer="true" placeholder="单位">
                      <Option v-for="(item,index) in units" :value="item.name" :key="'unit'+index">{{ item.name }}
                      </Option>
                    </Select>
                  </Col>
                  <Col span="4" push style="margin-right: 5px">属性类型
                    <Select v-model="virtualItem.type" :transfer="true" placeholder="属性类别">
                      <Option v-for="(item,index) in types" :value="item.name" :key="'type'+index">{{ item.name }}
                      </Option>
                    </Select>
                  </Col>
                <Col span="4" push style="margin-right: 5px">属性类别
                  <!-- <Select v-model="virtualItem.propertyType" :transfer="true" placeholder="属性类别"> -->
                  <Select v-model="virtualItem.propertyType" :transfer="true" placeholder="属性类别">
                    <Option v-for="(item,index) in propertyTypes" :value="item.value" :key="'propertyType'+index">{{ item.name }}
                    </Option>
                  </Select>
                </Col>
                  <Col span="3" push style="margin-right: 5px">
                    上限<Input v-model="virtualItem.lowLimit" placeholder="上限"/>
                  </Col>
                  <Col span="3" push>
                    下限<Input v-model="virtualItem.upperLimit" placeholder="下限"/>
                  </Col>
                </Row>
                <Row :gutter="15" style="padding-top: 15px">
                  <Col span="6" push>
                    日志 <Switch v-model="virtualItem.isLog" :true-value="1" :false-value="0" />
                  </Col>
                  <Col span="6" push>
                    采集 <Switch v-model="virtualItem.isGet" :true-value="1" :false-value="0" />
                  </Col>
                </Row>
                <Row :gutter="15" style="margin-top: 10px">
                  <Col span="24">
                    属性计算方式<Input v-model="virtualItem.formula" type="textarea" :autosize="{minRows: 3,maxRows: 10}"
                           placeholder="属性计算方式..."></Input>
                  </Col>
                </Row>
              </div>
              <div class="ddqq">
                <Row :gutter="24">
                  <Col span="12">
                    <Button type="default" @click="makeEmpty" long>置空</Button>
                  </Col>
                  <Col span="12">
                    <Button type="warning" long @click="doAdd"
                            :disabled="virtualItem.name === '' || virtualItem.unit ===''">
                      {{virtualItem.id ? '保存编辑':'保存新增'}}
                    </Button>
                  </Col>
                </Row>
              </div>
            </div>
          </Col>
        </Row>
      </TabPane>
      <TabPane name="fourTab" label="参数设定" class="padding5">
        <DevParams ref="devParams"></DevParams>
      </TabPane>
      <TabPane name="bTab" label="脚本代码" class="padding5">
        <ScriptPanel ref="refScript" @sonCallSave="saveOrUpd" ></ScriptPanel>
      </TabPane>
    </Tabs>
  </div>
</template>

<script>
  import ScriptPanel from '../type/ScriptPanel'
  import SelectPanel from '../big_device/SelectPanel'
  import DevParams from '../manage/DevParams.vue'
  export default {
    name: 'VirtualPanel',
    components: {
      SelectPanel,
      ScriptPanel,
      DevParams
    },
    mounted: function () {
      this.loadSpaceDatas()
      this.loadUnits()
      this.loadPropertyTypes()
      this.devTypeList()
      this.loadTypes()
    },
    data () {
      return {
        updateInit: true,
        deviceSpaceData: [], // 空间选择数据
        deviceTypeList: [], // 设备类型选项
        types: [], // 设备类型选项
        total: 0,
        devTypeObj: {},
        showTabPanel: 'aTab',
        saveingLoading: false,
        units: [],
        propertyTypes: [],
        defaultType: '',
        tableLoading: false,
        formValidate: {
          name: '',
          model: '',
          commAddr: '',
          readInterval: 1,
          deviceSpace: []
        },
        pageable: {
          page: 1,
          size: 10,
          type: 0,
          param: ''
        },
        columns1: [
          {
            title: 'ID',
            width: 80,
            fixed: 'left',
            key: 'devId'
          },
          {
            title: '属性名称',
            key: 'proName',
            fixed: 'left',
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '设备名称',
            key: 'devName',
            width: 200,
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '设备编号',
            key: 'snName',
            width: 120,
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '设备空间',
            key: 'spaceName',
            ellipsis: true,
            tooltip: true,
            align: 'center'
          },
          {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 100,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'info',
                    ghost: true,
                    size: 'small',
                    icon: 'ios-create-outline'
                  },
                  style: {
                    margin: '3px'
                    // color: '#2db7f5'
                  },
                  on: {
                    click: () => {
                      this.doCopy(params.row)
                    }
                  }
                }, '复制')
              ])
            }
            }
        ],
        data1: [],
        devType: '真实设备',
        virtualItem: {
          name: '',
          formula: '',
          isLog: 0,
          isGet: 1
        },
        editFun: '',
        virtualObj: {
          sn: '',
          name: '',
          model: '',
          deviceSpaceText: '',
          temporaryVariable: '',
          sort: ''
        },
        ruleValidate: {
          name: [
            {required: true, message: '必填项', trigger: 'blur'}
          ],
          sn: [
            {required: true, message: '必须以字母或下划线开头，编号可包含英文、数字、下划线', pattern: /^[a-zA-Z | _]([\u4e00-\u9fa5\w]{1,50})$/, trigger: 'blur'}
          ],
          deviceSpaceText: [
            {required: true, message: '必填项', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      optionClick: function (item) {
        if (!(item === undefined || item.id === undefined)) {
          this.devTypeObj = JSON.parse(JSON.stringify(item))
          // window.vm.$emit('deviceTypeObj', this.devTypeObj)
        }
      },
      // 设备类型list
      devTypeList: function () {
        let self = this
        let getData = {
          'size': 999,
          'page': 0
        }
        window.myapi.devType_list(getData).then(function (res) {
          self.deviceTypeList = []
          if (res.data.status === 200) {
            self.deviceTypeList = res.data.data.content
            if (self.deviceTypeList.length > 0) {
              let targetOne = self.deviceTypeList.find(item => item.useType === '虚拟设备类型')
              if (targetOne !== undefined) {
                // 设备类型初始化
                self.virtualObj.model = targetOne.model
                // 设备类型存储默认值
                self.devTypeObj = targetOne
              } else {
                self.$Message.info('无法获取‘虚拟设备类型’选项，请在设备类型配置名称为‘虚拟设备类型’的数据')
              }
            } else {
              self.$Message.info('无法获取设备类型数据,请配置。')
            }
          } else {
            let msg = res.data.msg ? res.data.msg : '请求数据失败!'
            self.$Message.error({ content: msg, duration: 5, closable: true })
          }
        }).catch(function (e) {
          if (e && e.response && e.response.data) {
            let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
            self.$Message.error({ content: msg, duration: 0, closable: true })
          }
        })
      },
      loadDatas () {
        this.data1 = []
        this.tableLoading = true
        // 加载数据
        window.myapi.do_post('iot/dev/virs', this.pageable).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            let result = resp.data.data
            this.total = result.total
            if (result.list.length > 0) {
              this.data1 = result.list
            }
          }
        }).finally(() => {
          this.tableLoading = false
        })
      },
      loadSpaceDatas () {
        // 加载数据
        window.myapi.do_post('iot/space/cas', this.pageable).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            this.deviceSpaceData = resp.data.data
          }
        }).finally(() => {
        })
      },
      loadUnits () {
        // 加载单位数据
        let pageab = {
          size: 9999,
          page: 0,
          groupType_eq: 1005
        }
        window.myapi.dict_list(pageab).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            this.units = resp.data.data.content
          }
        }).finally(() => {
        })
      },
      // 加载属性数据
      loadTypes: function () {
        let pageab = {
          size: 9999,
          page: 0,
          groupType_eq: 1007
        }
        window.myapi.dict_list(pageab).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            this.types = resp.data.data.content
          }
        }).finally(() => {
        })
      },
      // 编辑级联
      loadPropertyTypes () {
        // 加载属性类别数据
        let pageab = {
          size: 9999,
          page: 0,
          groupType_eq: 1004
        }
        window.myapi.dict_list(pageab).then(resp => {
          if (resp.status === 200 && resp.data.status === 200) {
            if (!resp.data.data.content.length) return false
            this.propertyTypes = resp.data.data.content
            this.defaultType = resp.data.data.content[0].value
          }
        }).finally(() => {
        })
      },
      cascaderFormat: function (labels, selectedData) {
        let self = this
        let index = labels.length - 1
        self.$nextTick(() => {
          if (selectedData.length > 0) {
            // this.virtualObj.deviceSpaceText = selectedData[index].label
            self.virtualObj = { ...self.virtualObj, ...{deviceSpaceText: ''} }
            if (self.updateInit) {
              // 弹框初始化后，会走到这一步，引起旧数据对传过来的值替换
              self.updateInit = false
              self.virtualObj.deviceSpaceText = labels[0]
            } else {
              self.virtualObj.deviceSpaceText = labels.join('>')
            }
            let spaceObj = {
                id: selectedData[index].value
            }
            self.virtualObj.iotSpace = spaceObj
          }
          return self.virtualObj.deviceSpaceText
        })
      },
      setAllDefault () {
        // 恢复默认设置
        this.virtualObj = {
          type: 1,
          deviceSpaceText: '',
          virtualItems: []
        }
        this.pageable = {
          page: 1,
          size: 10,
          type: 0,
          param: ''
        }
        this.makeEmpty()
        this.devType = '真实设备'
        // 清空 代码的填写
        this.$refs.refScript.makeDefault()
      },
      setDefaultDevType: function () {
        this.virtualObj.model = this.devTypeObj.useType
        window.vm.$set(this.virtualObj, 'model', this.devTypeObj.useType)
      },
      pageChange: function (index) {
        this.pageable.page = index
        this.loadDatas()
      },
      radioChange: function (txt) {
        if (txt === '真实设备') {
          this.pageable.type = 0
        } else {
          this.pageable.type = 1
        }
        this.pageable.page = 1
        this.loadDatas()
      },
      doQuery: function () {
        this.pageable.page = 1
        this.loadDatas()
      },
      acceptEditData (datas) {
        this.virtualObj = JSON.parse(JSON.stringify(datas))
        this.virtualObj.deviceSpaceText = this.virtualObj.temporaryVariable
        this.$refs.refScript.updateFormdata(JSON.parse(JSON.stringify(datas)))
        this.loadDatas()
      },
      doSave: function () {
        this.$refs['formValidate'].validate((valid) => {
          if (valid) {
              this.virtualObj.type = 1
              this.saveOrUpd()
          }
        })
      },
      // doEditPro: function (obj) {
      //  this.virtualItem = JSON.parse(JSON.stringify(obj))
      // },
      previewItem: function (obj) {
       this.virtualItem = JSON.parse(JSON.stringify(obj))
        console.log("ddddd", obj);
      },
      saveOrUpd: function () {
        this.saveingLoading = true
        let url = ''
        let method = ''
        if (this.virtualObj.id) {
          url = '/iot/dev/upd'
          method = 'PUT'
        } else {
          url = '/iot/dev/save'
          method = 'POST'
        }
        this.virtualObj.iotDevType = {
          id: this.devTypeObj.id
        }
        // 获取 脚本信息
        this.virtualObj.scriptSwitch = this.$refs.refScript.scriptObj.switch
        this.virtualObj.script = this.$refs.refScript.scriptObj.codes === '' ? '' : this.$refs.refScript.scriptObj.codes
        window.myapi.put_post(url, this.virtualObj, method).then((res) => {
          if (res.data.status === 200) {
            this.$Message.success('保存成功!')
            this.setAllDefault()
            this.callFatherRefresh()
            this.loadDatas()
          } else {
            let msg = res.data.msg ? res.data.msg : '保存失败！'
            this.$Message.error(msg)
          }
        }).catch(function (e) {
          let msg = e.response.data.message ? e.response.data.message : '保存失败!'
          this.$Message.error({duration: 0, closable: true, content: msg})
        }).finally(() => {
          this.saveingLoading = false
        })
      },
      callFatherRefresh () {
        this.$emit('tell-refresh')
      },
      delItem: function (index) {
        this.virtualObj.virtualItems.splice(index, 1)
        this.makeEmpty()
      },
      doCopy: function (row) {
        let getSnText = 'N/A'
        if (row.snName) {
          getSnText = row.snName
        }
        let text = getSnText + '.' + row.proName
        if (this.virtualItem.formula === '') {
          this.virtualItem.formula = text
        } else {
          this.virtualItem.formula = this.virtualItem.formula + '    ' + text
        }
      },
      // 设置设备类型只
      makeEmpty: function () {
        // 置空
        this.virtualItem = {
          name: '',
          formula: '',
          propertyType: this.propertyTypes[0].value,
          isLog: 0,
          isGet: 1
        }
        this.loadPropertyTypes()
      },
      doAdd: function () {
        // let reg = /^[a-zA-Z | _]([\u4e00-\u9fa5\w]{1,50})$/
        // if (!reg.exec(this.virtualItem.name)) {
        //   this.$Message.info('必须以字母或下划线开头，编号可包含英文、数字、下划线')
        //   return false
        // }
        if (!this.virtualItem.name || !this.virtualItem.unit) {
          this.$Message.info('请选择单位')
          return
        }
        // 判断是 新增的属性 还是编辑的属性
        if (this.virtualItem.id) {
          console.log(this.virtualItem.id)
          let findOne = this.virtualObj.virtualItems.findIndex(item => item.id === this.virtualItem.id)
          if (findOne > -1) {
            this.virtualObj.virtualItems.splice(findOne, 1, this.virtualItem)
            this.makeEmpty()
          } else {
            this.$Message.warning('找不到原来的编辑记录，请操作置空后新增数据')
          }
          return
        }
        // 去掉空格
        this.virtualItem.formula = this.virtualItem.formula.replace(/\s+/g, '')
        this.virtualObj.virtualItems.push(this.virtualItem)
        this.virtualItem = {
          formula: '',
          name: '',
          propertyType: this.propertyTypes[0].value,
          isLog: 0,
          isGet: 1
        }
        this.loadPropertyTypes()
      }
    }
  }
</script>

<style scoped>
.dxx{
  padding: 0px 20px;
}
  .ooa{
    margin-top: 10px;
  }
  .ooaa{
    margin-top: 30px;
  }
  .pagg{
    margin-top: 5px;
    text-align: right;
  }
  .ddxx{
    padding-left: 20px;
    font-size: 12px;
    margin-bottom: 5px;
    margin-top: 25px;
  }
  .ddqq{
    margin-top: 16px;
    text-align: center;
  }

.tableOne {
  width: 100%;
  border-spacing: 0px;
  table-layout: fixed;
}

table th,
td {
  border: 1px solid #e9eaec;
  margin: 0;
  padding: 3px;
}

table tr {
  margin: 0;
  height: 32px;
}

.columnStyle {
  text-align: center;
}

.padding5 {
  padding: 5px;
}
  .bppp{
    height: 370px;overflow-y: auto;
  }
</style>

<style>
  .daaa .ivu-form-item{
    margin-bottom: 20px;
  }
</style>
